#!/usr/bin/env node

const download = require("download-git-repo");
const fs = require('fs');
const minimist = require('minimist');
const path = require("path");
const prompts = require('prompts');
const { v4: uuid } = require('uuid');
const { version } = require('./package.json');

function isEmptyDir(path) {
  return fs.readdirSync(path).length === 0;
}

function logGreen(text) {
  console.log(`\x1B[32m${text}\x1b[0m\n`);
}

function logRed(text) {
  console.log(`\x1b[31;1m${text}\x1b[0m\n`);
}

function isValidPackageName(name) {
  return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(name);
}

/////////////////////////////////////////////////////

async function createApp() {
  console.log(`create-mp-package ${version} \n`);

  const { _: [name] } = minimist(process.argv.slice(2));
  if (name && !isValidPackageName(name)) {
    logRed(`Name ${name} is invalid`);
    return;
  }
  const targetDir = name || '.';

  // 创建目标目录
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir);
  }

  // 确保目标目录为空
  if (!isEmptyDir(targetDir)) {
    logRed(`Target directory ${targetDir} is not empty`);
    return;
  }

  const inputs = await prompts([{
    type: 'text',
    name: 'targetName',
    message: 'What is the targetName?',
    validate: (value) => {
      if (!value) {
        return 'Please enter targetName';
      }
      return true;
    }
  }, {
    type: 'text',
    name: 'targetCode',
    message: 'What is the targetCode?'
  }, {
    type: 'select',
    name: 'framework',
    message: 'What is the framework? [react|vue]',
    choices: [{ title: 'React', value: 'react' }, { title: 'Vue', value: 'vue' }],
    validate: (value) => {
      if (value !== 'react' && value !== 'vue') {
        return 'Please enter react or vue';
      }
      return true;
    }
  }]);

  console.log('cloning...');
  download(`direct:https://gitee.com/meta-platform/mp-package-sample-${inputs.framework}.git`,
    path.join(process.cwd(), targetDir), { clone: true }, async (err) => {
      if (err) {
        logRed(err);
      } else {
        console.log('done');

        // 更新package.json内容
        const package_text = fs.readFileSync(path.join(process.cwd(), targetDir, 'package.json'), { encoding: 'utf8' });
        const package_json = JSON.parse(package_text);

        package_json.id = uuid().replace(/-/g, '');
        package_json.name = 'mp-package-' + name;
        package_json.version = "0.0.1";
        package_json.targetName = inputs.targetName;
        package_json.targetCode = inputs.targetCode;
        package_json.description = "";
        package_json.repository = {};
        package_json.author = "";
        package_json.license = "";

        fs.writeFileSync(path.join(process.cwd(), targetDir, 'package.json'), JSON.stringify(package_json, null, 2));

        logGreen("Success");
      }
    });
}

createApp().catch((error) => {
  logRed(error);
});
